#!/usr/bin/env python
#
#Copyright 2011 Velin Georgiev
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.

''' Admin application file: "webapp/admin.py" - handles events related to the 
administration/index.html.'''

__author__ = 'Velin Georgiev'

import os
import re
from google.appengine.api import memcache, users
from google.appengine.ext import db, webapp
from google.appengine.ext.webapp.template import render
from google.appengine.ext.webapp.util import run_wsgi_app
from datamodel import tbl_posts, tbl_comments
#from xml.dom.minidom import parse
#from django.contrib.sitemaps import Sitemap
#from google.appengine.ext.db import djangoforms

class SubmitPost(webapp.RequestHandler):
    def post(self):
		title = self.request.get('title')
		content = self.request.get('content')
		category = self.request.get('category')
		if self.request.get('visible'): 
			visible=True
		else:
			visible=False
		#Simple Validation
		validate_title = re.search("\S", title)
		validate_content = re.search("\S", content)
		validate_category = re.search("\S", category)
		if validate_title == None or validate_content == None or validate_category == None:
			self.response.out.write("<html><head><body>The Title and Content fields are mandatory.<br/><a href=\"javascript:history.back();\" >Go Back</a></body></head></html>")
			return
		#Inserting the data into the datamodel
		tbl_posts().new_item(title, content, category, visible)
		memcache.delete('posts')
		memcache.delete('categories')
		self.redirect('/administrator/')
		
class EditPost(webapp.RequestHandler):
    def post(self):
		title = self.request.get('title')
		content = self.request.get('content')
		category = self.request.get('category')
		if self.request.get('visible'): 
			visible=True
		else:
			visible=False
		id = self.request.get('post_id')
		memcache.delete('comments')
		memcache.delete('posts')
		memcache.delete('categories')
		if self.request.get('posts_modify_action') == "Save":
			#Simple Validation
			validate_title = re.search("\S", title)
			validate_content = re.search("\S", content)
			validate_category = re.search("\S", category)
			if validate_title == None or validate_content == None or validate_category == None:
				self.response.out.write("<html><head><body>The Title and Content fields are mandatory.<br/><a href=\"javascript:history.back();\" >Go Back</a></body></head></html>")
				return
			tbl_posts().update_item(id, title, content, category, visible)
			self.redirect('/administrator/?id='+str(id))
		if self.request.get('posts_modify_action') == "Delete":
			tbl_posts().delete_item(id)
			tbl_comments().delete_all_related_items(id)
			self.redirect('/administrator/')
		
class EditComment(webapp.RequestHandler):	
	def post(self):
		comment_id = self.request.get('comment_id')
		visibility = self.request.get('visible_comment_'+comment_id)
		if visibility: 
			visible=True
		else:
			visible=False
		if self.request.get('comments_modify_action') == "Save":
			comment_text = self.request.get('comment_'+str(comment_id)).replace('comment_', '')
			#Simple Validation
			validate_comment = re.search("\S", comment_text)
			if validate_comment == None:
				self.response.out.write("<html><head><body>The Title and Content fields are mandatory.<br/><a href=\"javascript:history.back();\" >Go Back</a></body></head></html>")
				return
			tbl_comments().update_item(comment_id, comment_text, visible)
		if self.request.get('comments_modify_action') == "Delete":
			tbl_comments().delete_item(comment_id)
		memcache.delete('comments')
		self.redirect('/administrator/?id='+str(self.request.get('post_id')))
		
class MainHandler(webapp.RequestHandler):		
	def get(self):
		strTitlesList = ""
		qrySinglePostId = ""
		qrySinglePost = ""
		qryPostComments = ""
		strCommentsList = ""
		strCommentID = ""
		strVisibiliy = ""
		listCategories = []
		user = users.get_current_user()		
		posts = memcache.get('posts')
		categories = memcache.get('categories')
		#Get the titles list
		selected_category = self.request.get('cat') #form get
		if selected_category != "" and selected_category != "All":
			posts = db.Query(tbl_posts()).filter('category =', selected_category)
		else:
			if not posts: posts = tbl_posts().all().order('-date').fetch(100)
		memcache.add('posts', posts)
		if selected_category == "": selected_category = "All"
		for item in posts:
			strTitlesList = strTitlesList + ('<a href="/administrator/?id=%d&amp;cat=%s">%s</a><br/>' % (item.key().id(), selected_category.replace(" ","+"), item.title))
		if not categories:
			#Get categories
			categories = tbl_posts().select_distinct_category()
			memcache.add('categories', categories)
		if self.request.get('id'):	
			query = tbl_posts()
			qrySinglePost = query.get_by_id(long(self.request.get('id')))
			if qrySinglePost.visible:
				checked = "checked=\"checked\""
			else:
				checked = ""
			strVisibiliy = "<input type=\"checkbox\" name=\"visible\" id=\"visible\"" + checked+ "/>"
			qrySinglePostId = qrySinglePost.key().id()
		comments = memcache.get('comments')
		if not comments:
			if self.request.get('id'):	
				query = db.Query(tbl_comments)
				qryPostComments = query.filter('post_id =', long(self.request.get('id')))
				if qryPostComments:
					for item in qryPostComments:
						strCommentID = item.key().id()
						if item.visible:
							checked = "checked=\"checked\""
						else:
							checked = ""
						strCommentsList = strCommentsList + "ID:" + str(strCommentID) + " [" + str(item.date.day)+"/"+str(item.date.month)+"/"+str(item.date.year)+"]<strong> "+str(item.author)+"</strong>:<div style=\"text-align:right;\"><a href=\"javascript:editComment('Save', '"+str(strCommentID)+"');\" >Save</a> | <a href=\"javascript:editComment('Delete', '"+str(strCommentID)+"');\" >Delete</a> | Visible <input type=\"checkbox\" name=\"visible_comment_" + str(strCommentID) + "\" id=\"visible_comment_" + str(strCommentID) + "\" "+checked+" /></div><textarea id=\"comment_" + str(strCommentID) + "\" name=\"comment_" + str(strCommentID) + "\" style=\"width:100%;min-height:400px;\" >"+item.comment+"</textarea><br/>----<br/>"
				memcache.add('comments', comments)
		context = {
			'user': user,
			'login': users.create_login_url(self.request.uri),
			'logout': users.create_logout_url(self.request.uri),
			'posts': posts,
			'post_id': qrySinglePost,
			'comments': qryPostComments,
			'categories': categories,
			'titles_list': strTitlesList,
			'article_id': qrySinglePostId,
			'comments_list':strCommentsList,
			'visibiliy': strVisibiliy,
		}
		tmpl = os.path.join(os.path.dirname(__file__), 'administrator','index.html')
		self.response.out.write(render(tmpl, context))
		
application = webapp.WSGIApplication([
    ( '/administrator/', MainHandler),
	( '/administrator/new_post', SubmitPost),
	( '/administrator/edit_post', EditPost),
	( '/administrator/edit_comment', EditComment),
], debug=True)

def main():
    run_wsgi_app(application)

if __name__ == '__main__':
    main()